﻿package kizzo.comm 
{
	import flash.events.DataEvent;
	import flash.events.EventDispatcher;
	import flash.net.LocalConnection;
	
	/**
	 * ...
	 * @author 
	 */
	public class CommSession extends EventDispatcher	
	{		
		
		public static const CONNECTED:String = "CONNECTED";
		public static const DATA:String = "DATA";
		public static const ERROR:String = "ERROR";
		
		private var id:String;
		
		public var connected:Boolean;
		
		private var connection:LocalConnection;
		
		public function CommSession(id:String) 
		{
			this.id = id;
			this.connected = false;	
			this.connection = new LocalConnection();	
			this.connection.client = this;
			this.connection.connect(id);
		}
		
		
		public function connect():void
		{ 
			if (this.connected)
				throw new Error("Cannot use connect method on a connected CommSession");
			
			var xml:XML = <connect user="John" pass="aaaa"/>;
			this.connection.send("_server", "data_hnd", xml);
		}
		
		public function wait_for_connection():void
		{
			if (this.connected)
				throw new Error("Cannot wait for connection on an already connected CommSession");
				
			this.connection.connect("_server");			
		}
		
		public function send(xml:XML):void
		{
			
		}
		
		public function data_hnd(xml:XML):void
		{
			var data_event:DataEvent = new DataEvent(DATA);
			
			this.connection.send("_server", "data_hnd", xml); 
			
			data_event.data = xml.toXMLString();
			dispatchEvent(data_event);
		}		
	}
	
}